﻿using RimWorld;
using Verse;
using System.Collections.Generic;
using System.Linq;
using Verse.AI.Group;
using System;

namespace RimZombieGirl
{
    public class IncidentWorker_GiveDaoFriendlyRaid : IncidentWorker_GiveDaoFriendlyBase
    {
        protected override bool ExecuteFriendlyEvent(IncidentParms parms, Map map, Faction daoFaction)
        {
            if (!IsAberrantRaidOngoing(map))
                return false;

            IntVec3 spawnCenter;
            if (!RCellFinder.TryFindRandomPawnEntryCell(out spawnCenter, map, CellFinder.EdgeRoadChance_Neutral, true, null))
                return false;

            PawnGroupMakerParms groupParms = new PawnGroupMakerParms
            {
                groupKind = ZombieDefOf.RI_Dao_FriendlyRaid,
                tile = map.Tile,
                inhabitants = false,
                points = Math.Max(StorytellerUtility.DefaultThreatPointsNow(map), 200f),
                faction = daoFaction,
                ideo = daoFaction.ideos?.PrimaryIdeo,
                traderKind = null,
                generateFightersOnly = true,
                dontUseSingleUseRocketLaunchers = true,
                raidStrategy = RaidStrategyDefOf.ImmediateAttack,
                forceOneDowned = false,
                seed = 114514,
                raidAgeRestriction = null,
                ignoreGroupCommonality = false
            };


            List<Pawn> pawns = PawnGroupMakerUtility.GeneratePawns(groupParms).ToList();

            if (pawns.Count == 0)
                return false;

            // 在地图边缘生成
            foreach (Pawn pawn in pawns)
            {
                GenSpawn.Spawn(pawn, CellFinder.RandomClosewalkCellNear(spawnCenter, map, 10), map, Rot4.Random);
            }


            LordJob_AssistColony lordJob = new LordJob_AssistColony(daoFaction, spawnCenter);

            LordMaker.MakeNewLord(daoFaction, lordJob, map, pawns);

            TaggedString letterText = "RI_DaoFriendlyRaid.letterText".Translate();
            TaggedString letterLabel = "RI_DaoFriendlyRaid.letterLabel".Translate();
            SendStandardLetter(letterLabel, letterText, LetterDefOf.PositiveEvent, parms, pawns, Array.Empty<NamedArgument>());

            return true;
        }
        private bool IsAberrantRaidOngoing(Map map)
        {
            return map.attackTargetsCache.TargetsHostileToColony
                .OfType<Pawn>()
                .Any(p => p.Faction != null && p.Faction.def.defName == "RI_Faction_Aberrant");
        }


    }
}
